// pages/top_up/top_up.js
var api = require('../../api/api');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    top_up_amounts: [{
        amount: "40.00"
      },
      {
        amount: "50.00"
      },
      {
        amount: "60.00"
      },
      {
        amount: "70.00"
      },
      {
        amount: "80.00"
      },
      {
        amount: "90.00"
      }
    ],
    lists: [],
    rules: [],
    curindex: 0,
    userInfo: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.commonMoneys();
    let userInfo = wx.getStorageSync('userInfo');
    this.setData({
      userInfo
    })
  },
  payMoney() {
    let that = this;
    let location = wx.getStorageSync('Location');
    api.post('/user/payMoney', {
      id: this.data.lists[this.data.curindex].id,
      latitude: location.latitude,
      longitude: location.longitude
    }).then(res => {

      wx.requestPayment({
        ...res.payInfo,
        success: function (res) {
          console.log('success:' + JSON.stringify(res));
          wx.showToast({
            title: '充值成功',
            icon: 'none',
            success: function () {
              setTimeout(() => {
                that.getUserInfo();
              }, 1000)

            }
          })
        },
        fail: function (err) {
          console.log('fail:' + JSON.stringify(err));
          if (err.errMsg == "requestPayment:fail cancel") {
            wx.showToast({
              title: '取消支付',
              icon: 'none',
              duration: 3000
            })
          } else {
            wx.showToast({
              title: JSON.stringify(err),
              icon: 'none',
              duration: 3000
            })
          }
        }
      });


    })
  },
  //获取用户信息
  getUserInfo() {
    api.get('/user').then(res => {
      wx.setStorageSync('userInfo', res.userInfo)
      this.setData({
        userInfo: res.userInfo
      })
    })
  },
  commonMoneys() {
    let location = wx.getStorageSync('Location')
    api.get('/common/moneys', {
      longitude: location.longitude,
      latitude: location.latitude
    }).then(res => {
      this.setData({
        lists: res.items,
        rules: res.rules
      })
    })
  },
  //点击充值套餐
  click_top_up_item(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      curindex: index
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})